package com.yizn.learn.Condition;

import org.w3c.dom.css.Counter;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 代码实现了一个基于CAS线程安全的计数器方法safeCount和一个线程不安全的计数器count
 *
 * @author yisl
 * @create 2019-07-25 15:55
 */
public class Conter {

    private int i = 0;
    private AtomicInteger atomicI = new AtomicInteger();

    public static void main(String[] args) {

        final Conter conter = new Conter();

        long start = System.currentTimeMillis();
        ArrayList<Thread> ts = new ArrayList<Thread>(600);
        for (int j = 0; j<600; j++){
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10000; i++){
                        conter.safeCount();
                        conter.count();
                    }
                }
            });
            ts.add(t);
        }

        for(Thread thread : ts){
            thread.start();
        }

        for(Thread thread : ts){
            try {
                thread.join();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }

        System.out.println(conter.atomicI.get());
        System.out.println(conter.i);
        System.out.println(System.currentTimeMillis()-start);


    }

    private void safeCount(){
        for (;;){
            int i = atomicI.get();
            boolean suc = atomicI.compareAndSet(i, ++i);
            if (suc){
                break;
            }
        }
    }

    private void count(){
        i++;
    }


}
